package web.weibo.controller;

import web.weibo.mapper.MapperUser;
import web.weibo.model.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import web.weibo.service.ServiceTodo;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Controller
public class ControllerTodo {

    private MapperUser mapperUser;
    private ServiceTodo serviceTodo;

    ControllerTodo(MapperUser mapperUser, ServiceTodo serviceTodo) {
        this.mapperUser = mapperUser;
        this.serviceTodo = serviceTodo;
    }

    @GetMapping("/todo/all")
    public ModelAndView all(HttpServletRequest request) {
        // 显示所有 todo
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        ArrayList<Todo> todos = this.serviceTodo.currentUserTodos(currentUser);
        ModelAndView modelAndView = new ModelAndView("todo_all");
        modelAndView.addObject("todos", todos);
        return modelAndView;
    }

    @GetMapping("/todo/add")
    public ModelAndView add(String content, HttpServletRequest request) {
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        this.serviceTodo.add(content, currentUser);
        return new ModelAndView("redirect:/todo/all");
    }

    @GetMapping("/todo/delete")
    public ModelAndView delete(HttpServletRequest request, int id) {
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        this.serviceTodo.delete(id, currentUser);
        return new ModelAndView("redirect:/todo/all");
    }

    @GetMapping("/todo/edit")
    public ModelAndView edit(HttpServletRequest request, int id) {
        ModelAndView modelAndView = new ModelAndView("todo_edit");
        modelAndView.addObject("todo_id", id);
        return modelAndView;
    }

    @GetMapping("/todo/update")
    public ModelAndView update(HttpServletRequest request, int id, String content) {
        // 拿到请求数据
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        this.serviceTodo.update(id, content, currentUser);
        return new ModelAndView("redirect:/todo/all");
    }
}